package com.cheng.im.service.massage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cheng.im.common.bean.msg.ProtoMsgV1;
import com.cheng.im.common.constants.MQConstants;
import com.cheng.im.common.constants.RedisConstants;
import com.cheng.im.service.common.eunms.DelFlagEnum;
import com.cheng.im.service.conversation.service.ImConversationSetService;
import com.cheng.im.service.group.mapper.ImGroupMessageHistoryMapper;
import com.cheng.im.service.massage.mapper.ImMessageBodyMapper;
import com.cheng.im.service.massage.mapper.ImMessageHistoryMapper;
import com.cheng.im.service.message.domain.ImMessageBody;
import com.cheng.im.service.message.domain.ImMessageHistory;
import com.cheng.im.service.mq.RocketMQProduce;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class MessageStoreService {

    @Resource
    ImMessageBodyMapper imMessageBodyMapper;

    @Resource
    ImGroupMessageHistoryMapper imGroupMessageHistoryMapper;

    @Resource
    ImMessageHistoryMapper imMessageHistoryMapper;

    @Resource
    RocketMQProduce rocketMQProduce;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    ImConversationSetService conversationService;

    @Transactional
    public void storeP2PMessage(ProtoMsgV1.Message messageContent){
        // todo: 消息队列解耦
        // rocketMQProduce.sendMessage(MQConstants.MESSAGE_2_STORE, messageContent);

        // 存储单聊消息
        ImMessageBody imMessageBody = extractMessageBody(messageContent);
        imMessageBodyMapper.insert(imMessageBody);
        // 更新历史消息
        List<ImMessageHistory> imMessageHistories = extractToP2PMessageHistory(messageContent, imMessageBody);
        // todo: 批量插入
        for (ImMessageHistory imMessageHistory : imMessageHistories) {
            imMessageHistoryMapper.insert(imMessageHistory);
        }
    }

    private List<ImMessageHistory> extractToP2PMessageHistory(ProtoMsgV1.Message messageContent, ImMessageBody imMessageBody) {
        ProtoMsgV1.MessageRequest messageRequest = messageContent.getMessageRequest();

        List<ImMessageHistory> imMessageHistories = new ArrayList<>();

        ImMessageHistory imMessageHistory = new ImMessageHistory();
        BeanUtils.copyProperties(imMessageBody, imMessageHistory);
        imMessageHistory.setOwnerId(messageRequest.getFrom());
        imMessageHistory.setFromId(messageRequest.getFrom());
        imMessageHistory.setToId(messageRequest.getTo());
        imMessageHistory.setSequence(messageContent.getSequence());

        ImMessageHistory imMessageHistory1 = new ImMessageHistory();
        BeanUtils.copyProperties(imMessageBody, imMessageHistory1);
        imMessageHistory1.setOwnerId(messageRequest.getTo());
        imMessageHistory1.setFromId(messageRequest.getFrom());
        imMessageHistory1.setToId(messageRequest.getTo());
        imMessageHistory1.setSequence(messageContent.getSequence());

        imMessageHistories.add(imMessageHistory);
        imMessageHistories.add(imMessageHistory1);

        return imMessageHistories;
    }

    private ImMessageBody extractMessageBody(ProtoMsgV1.Message messageContent) {
        ProtoMsgV1.MessageRequest messageRequest = messageContent.getMessageRequest();

        ImMessageBody imMessageBody = new ImMessageBody();

        imMessageBody.setAppId(messageContent.getAppId());
        imMessageBody.setMessageKey(messageRequest.getMsgId());
        imMessageBody.setMessageBody(messageRequest.getContent());
//        imMessageBody.setSecurityKey();
        imMessageBody.setMessageTime(messageRequest.getTime());
        imMessageBody.setCreateTime(System.currentTimeMillis());
//        imMessageBody.setExtra(messageRequest.getExtra());
        imMessageBody.setDelFlag(DelFlagEnum.NORMAL.getCode());

        return imMessageBody;
    }


    public void storeGroupMessage(ProtoMsgV1.Message messageContent){
        rocketMQProduce.sendMessage(MQConstants.GROUP_MESSAGE_2_STORE, messageContent);
    }


    public void setMessageFromMessageIdCache(String appId, String sdkUuid, Object messageContent){
        //appid : cache : messageId
        String key =appId + ":" + RedisConstants.cacheMessage + ":" + sdkUuid;
        stringRedisTemplate.opsForValue().set(key,JSONObject.toJSONString(messageContent),300, TimeUnit.SECONDS);
    }

    public <T> T getMessageFromMessageIdCache(String appId, String messageId, Class<T> clazz){
        //appid : cache : messageId
        String key = appId + ":" + RedisConstants.cacheMessage + ":" + messageId;
        String msg = stringRedisTemplate.opsForValue().get(key);
        if(StringUtils.isBlank(msg)){
            return null;
        }
        return JSONObject.parseObject(msg, clazz);
    }

    /**
     * @description: 存储单人离线消息
     * @param
     * @return void
     * @author lld
     */
//    public void storeOfflineMessage(OfflineMessageContent offlineMessage){
//
//        // 找到fromId的队列  appid:offlineMessage:fromId
//        String fromKey = offlineMessage.getAppId() + ":" + Constants.RedisConstants.OfflineMessage + ":" + offlineMessage.getFromId();
//        // 找到toId的队列
//        String toKey = offlineMessage.getAppId() + ":" + Constants.RedisConstants.OfflineMessage + ":" + offlineMessage.getToId();
//
//        ZSetOperations<String, String> operations = stringRedisTemplate.opsForZSet();
//        //判断 队列中的数据是否超过设定值
//        if(operations.zCard(fromKey) > appConfig.getOfflineMessageCount()){
//            operations.removeRange(fromKey,0,0);
//        }
//        offlineMessage.setConversationId(conversationService.convertConversationId(
//                ConversationTypeEnum.P2P.getCode(),offlineMessage.getFromId(),offlineMessage.getToId()
//        ));
//        // 插入 数据 根据messageKey 作为分值
//        operations.add(fromKey,JSONObject.toJSONString(offlineMessage),
//                offlineMessage.getMessageKey());
//
//        //判断 队列中的数据是否超过设定值
//        if(operations.zCard(toKey) > appConfig.getOfflineMessageCount()){
//            operations.removeRange(toKey,0,0);
//        }
//
//        offlineMessage.setConversationId(conversationService.convertConversationId(
//                ConversationTypeEnum.P2P.getCode(),offlineMessage.getToId(),offlineMessage.getFromId()
//        ));
//        // 插入 数据 根据messageKey 作为分值
//        operations.add(toKey,JSONObject.toJSONString(offlineMessage),
//                offlineMessage.getMessageKey());
//
//    }


    /**
     * @description: 存储单人离线消息
     * @param
     * @return void
     * @author lld
     */
//    public void storeGroupOfflineMessage(OfflineMessageContent offlineMessage
//            ,List<String> memberIds){
//
//        ZSetOperations<String, String> operations = stringRedisTemplate.opsForZSet();
//        //判断 队列中的数据是否超过设定值
//        offlineMessage.setConversationType(ConversationTypeEnum.GROUP.getCode());
//
//        for (String memberId : memberIds) {
//            // 找到toId的队列
//            String toKey = offlineMessage.getAppId() + ":" +
//                    Constants.RedisConstants.OfflineMessage + ":" +
//                    memberId;
//            offlineMessage.setConversationId(conversationService.convertConversationId(
//                    ConversationTypeEnum.GROUP.getCode(),memberId,offlineMessage.getToId()
//            ));
//            if(operations.zCard(toKey) > appConfig.getOfflineMessageCount()){
//                operations.removeRange(toKey,0,0);
//            }
//            // 插入 数据 根据messageKey 作为分值
//            operations.add(toKey,JSONObject.toJSONString(offlineMessage),
//                    offlineMessage.getMessageKey());
//        }
//
//
//    }
}
